package com.service.dialtest.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.config.utils.StringUtils;
import com.service.dialtest.dao.CloudUserDao;
import com.service.dialtest.dto.DialTestDto;
import com.service.dialtest.entity.CloudUserInfo;
import com.service.config.utils.RedisUtil;
import com.service.dialtest.model.DialingMetric;
import com.service.dialtest.service.DialTestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.service.config.constant.ApiUrlConstants.*;

/**
 * @Description:
 * @Author: hjl
 * @Date: 2021/10/28 19:44
 */
@Component
@Async
@Slf4j
public class ScheduleService {
    @Autowired
    private CloudUserDao cloudUserDao;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    RestTemplate restTemplate;
    @Resource
    private DialTestService dialTestService;

    // @Scheduled(fixedDelay = 20000)
    @Scheduled(cron = "* * */24 * * ?")
//    @Async("taskExecutor")
    @Scheduled(cron = "*/30 * * * * ?")
   // @Async("taskExecutor")
    public void schedule(){
        this.getLoginUserDispose();
    }

    public void getLoginUserDispose() {
        //查找在线用户Api账号列表
        List<CloudUserInfo> userInfos = new ArrayList<>();
        List<CloudUserInfo> cloudUserInfoList = cloudUserDao.queryAll(new CloudUserInfo());
        cloudUserInfoList.forEach(cloudUserInfo -> {
            Set<String> strings = redisUtil.redisLike(cloudUserInfo.getUserId());
            if (strings.size()>0 ) {
                userInfos.add(cloudUserInfo);
            }
        });

        //筛选出来用户api账号状态正常的获取数据
        List<CloudUserInfo> list = new ArrayList<>();
        userInfos.forEach(user -> {
            if (user.getStatus()) {
                if (user.getDomain() == null || "".equals(user.getDomain())) {
                    user.setDomain("naas");
                }
                list.add(user);
            }
        });


        if (list.size() > 0) {
            //根据用户id分组
            Map<String, List<CloudUserInfo>> map = new HashMap<>();
            list.stream().collect(Collectors.groupingBy(CloudUserInfo::getUserId))
                    .forEach(map::put);
            map.entrySet().forEach(userList -> {
                List<CloudUserInfo> cloudUserInfos = userList.getValue();
                for (CloudUserInfo cloudUserInfo : cloudUserInfos) {
                    HttpHeaders header = getHttpHeader(cloudUserInfo);
                    List<DialTestDto> dialTestDtos = getDialTest(header, cloudUserInfo.getDomain());
                    if (dialTestDtos != null && dialTestDtos.size() > 0) {
                        redisUtil.delete(cloudUserInfo.getUserId().concat("_dialTest"));
                        redisUtil.setList(cloudUserInfo.getUserId().concat("_dialTest"), dialTestDtos);
                    }
                }
            });

        } else {
            log.info("The Online User list is null!");
        }
    }

    /**
     * 获取站点site
     *
     * @param requestHeaders
     * @return
     */
    public List<DialTestDto> getDialTest(HttpHeaders requestHeaders, String domain) {
        //获取站点
        JSONArray data = null;
        boolean flag = true;
        int pageIndex = 1;
        List<DialTestDto> dialTestDtos = new ArrayList<>();
        Map map = new HashMap();
        long currentMillis = System.currentTimeMillis();
        map.put("startTime", currentMillis-7*24*60*60*1000);
        map.put("endTime", currentMillis);
        map.put("pageSize", 50);
        try {
            while (flag) {
                map.put("currPage", pageIndex);
                HttpEntity<Map> requestEntity = new HttpEntity<>(map,requestHeaders);
                if(!StringUtils.isEmpty(domain) && domain.equals("49.4.52.44:26335")){
                    ResponseEntity<JSONObject> response = restTemplate.exchange("https://" + domain + DIAL_TEST_URL , HttpMethod.POST, requestEntity, JSONObject.class);
                    data = response.getBody().getJSONArray("data");
                }

                if (data != null && data.size()>0) {
                    dialTestDtos.addAll(data.toJavaList(DialTestDto.class));
                    pageIndex++;
                } else {
                    flag = false;
                }
            }
            //模拟拨测数据
//            dialTestDtos=getDialTest();
            return dialTestDtos;
        } catch (Exception e) {
            log.error("debug getSites ==>" + e.getMessage());
            return null;
        }
    }

    private List<DialTestDto> getDialTest() {
        List<DialTestDto> dialTestDtos=new ArrayList<>();
        /*DialTestDto dialTestDto1=new DialTestDto("TA","Shangri-La Tanjung Aru","",60,8,7.5f,5,46,36.83f,1.52f,8.44f,5.08f,0.79f,39.72f,6.98f,-85,-14,-52,5,8,0.08f,0.13f,0.78f,0);
        DialTestDto dialTestDto2=new DialTestDto("RR","Shangri-La Rasa Ria Resort","HUAWEI JSN-L22,HUAWEI",265,14,18.9f,3,5289,512.84f,0f,94f,6.05f,0f,19.89f,5.62f,-91,-22,-58,5,42,0.16f,0.14f,0.7f,0);
        DialTestDto dialTestDto3=new DialTestDto("SLW","Shangri-la WenZhou","Samsung Galaxy Note8",28,5,5.6f, 19.19f,160.8f,48.95f, 0.46f,14.49f,7.88f, 0.66f,9.49f,8.22f, 0,0,0, 0,0,0f,0f,0f,0);
        DialTestDto dialTestDto4=new DialTestDto("SLT","Shangri-La Tian Jin","",2,1,2.0f,84,85,84.5f,10.65f,10.72f,10.69f,11.39f,11.46f,11.43f,-52,-51,-52,0,0,0f,0f,1f,0);
        DialTestDto dialTestDto5=new DialTestDto("SLA","Shangri-La Abu Dhabi","",21,3,7.0f,71,100,75.62f,8.72f,23.97f,18.42f,6.07f,24.5f,15.77f,-82,-35,-57,4,3,0.19f,0.14f,0.67f,0);
        DialTestDto dialTestDto6=new DialTestDto("SLI","Shangri-La Bosphorus Istanbul","",154,7,22.0f,52,70,55.75f,9.23f,38.07f,19.94f,8.9f,50.58f,33.61f,-64,-28,-55,0,0,0f,0f,1.0f,0);
        DialTestDto dialTestDto7=new DialTestDto("HJH","Hotel Jen Hong Kong","",116,12,9.7f,36,58,38.53f,0.74f,26.12f,20.16f,0f,30.71f,18.52f,-85,-32,-54,18,9,0.16f,0.08f,0.77f,0);
        DialTestDto dialTestDto8=new DialTestDto("KHP","Kerry Hotel Pudong Shanghai","",32,6,5.3f,56,68,60.34f,10.09f,32.41f,20.4f,2.74f,36.97f,22.21f,-65,-31,-47,0,0,0f,0f,1f,0);
        DialTestDto dialTestDto9=new DialTestDto("KS","Kowloon Shangri-La,Hong Kong","",110,7,15.7f,38,999,50.1f,0.62f,39.39f,23.34f,0.36f,39.69f,22.24f,-77,-23,-52,6,11,0.05f,0.10f,0.85f,0);
        DialTestDto dialTestDto10=new DialTestDto("KHH","Kerry Hotel Hong Kong","",350,22,15.9f,35,999,49.95f,2.4f,56.35f,26.35f,3.03f,60.74f,32.98f,-78,-18,-45,10,13,0.03f,0.04f,0.93f,0);
        DialTestDto dialTestDto11=new DialTestDto("HJT","Hotel Jen Tanglin Singapore","Samsung Galaxy A50",68,10,6.8f,5,28,7.21f,4.96f,30.01f,26.7f,3.11f,30.38f,27.18f,-82,-32,-59,12,3,0.18f,0.04f,0.78f,7);
        DialTestDto dialTestDto12=new DialTestDto("HBK","Island Shangri-La Hotel,Hong Kong","Samsung Galaxy Note8",12,4,3.0f,55,62,57.67f,9.32f,42.48f,27.96f,12.03f,27.07f,22.31f,-71,-40,-53,1,0,0.08f,0f,0.92f,0);
        DialTestDto dialTestDto13=new DialTestDto("SLP","Shangri-La Hotel Shanghai","",135,8,16.9f,36,67,47.85f,18.4f,44.33f,32.41f,12.1f,41.73f,32.78f,-71,-1,-52,1,1,0.01f,0.01f,0.99f,0);
        DialTestDto dialTestDto14=new DialTestDto("SLY","Shangri-La Hotel,Yangzhou","Huawei P9",121,10,12.1f,62,999,416.79f,4.18f,55.89f,32.64f,1.69f,46.42f,33.24f,-86,-29,-54,9,11,0.07f,0.09f,0.83f,9);
        DialTestDto dialTestDto15=new DialTestDto("IS","Island Shangri-La Hotel,Hong Kong","Samsung Galaxy Note 8",142,7,20.3f,36,54,40.08f,10.3f,109.83f,42.48f,6.27f,366.13f,56.14f,-75,-38,-57,8,21,0.06f,0.15f,0.8f,7);
        dialTestDtos.add(dialTestDto1);
        dialTestDtos.add(dialTestDto2);
        dialTestDtos.add(dialTestDto3);
        dialTestDtos.add(dialTestDto4);
        dialTestDtos.add(dialTestDto5);
        dialTestDtos.add(dialTestDto6);
        dialTestDtos.add(dialTestDto7);
        dialTestDtos.add(dialTestDto8);
        dialTestDtos.add(dialTestDto9);
        dialTestDtos.add(dialTestDto10);
        dialTestDtos.add(dialTestDto11);
        dialTestDtos.add(dialTestDto12);
        dialTestDtos.add(dialTestDto13);
        dialTestDtos.add(dialTestDto14);
        dialTestDtos.add(dialTestDto15);*/
        return dialTestDtos;
    }

    /**
     * 获取用户token
     *
     * @param cloudUserInfo
     */
    public HttpHeaders getHttpHeader(CloudUserInfo cloudUserInfo) {

        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());

        String userName = cloudUserInfo.getTenantName();
        String password = cloudUserInfo.getTenantPwd();
        String domain = cloudUserInfo.getDomain();
        String token = "";

        try {
            if (redisUtil.exist(userName.concat("token"))) {
                token = redisUtil.getValue(userName.concat("token"));
            } else {
                //获取token
                token = this.getToken(userName, password, requestHeaders, domain);
                redisUtil.set(userName.concat("token"), 1, token, 1);
            }
            //获取站点
            requestHeaders.add("X-AUTH-TOKEN", token);
            return requestHeaders;
        } catch (Exception e) {
            log.error("token Access failure!");
            return null;
        }
    }

    /**
     * 获取token
     *
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public String getToken(String username, String password, HttpHeaders requestHeaders, String domain) {
        //获取token
        Map map = new HashMap();
        map.put("userName", username);
        map.put("grantType", "password");
        map.put("value", password);
        try {
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            if(!StringUtils.isEmpty(domain) && domain.equals("naas")){
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://" + domain + CLOUD_CAMPUS_TOKEN_URL, HttpMethod.POST, requestEntity, JSONObject.class);
                return response.getBody().getJSONObject("data").getString("token_id");
            }else if(!StringUtils.isEmpty(domain)){
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://" +  DIAL_TEST_TOKEN_URL, HttpMethod.PUT, requestEntity, JSONObject.class);
                return response.getBody().getString("accessSession");
            }
            return null;
        } catch (Exception e) {
            log.error("debug Token ==>" + e.getMessage());
            return null;
        }
    }
}
